/*
 * softspi.c
 *
 *  Created on: Jan 4, 2013
 *      Author: rleitner
 */

#include "../core/softspi.h"
#include "../core/gpio.h"

void init_spi (){
	gpioSetDir (SOFTSPI_CS1_PORT,  SOFTSPI_CS1_PIN,  gpioDirection_Output);
	gpioSetDir (SOFTSPI_MOSI_PORT, SOFTSPI_MOSI_PIN, gpioDirection_Output);
	gpioSetDir (SOFTSPI_SCLK_PORT, SOFTSPI_SCLK_PIN, gpioDirection_Output);

	gpioSetValue (SOFTSPI_CS1_PORT,  SOFTSPI_CS1_PIN,  1);
	gpioSetValue (SOFTSPI_MOSI_PORT, SOFTSPI_MOSI_PIN, 0);
	gpioSetValue (SOFTSPI_SCLK_PORT, SOFTSPI_SCLK_PIN, 0);
}
void write_spi (unsigned char data_out){       //msb first
unsigned char loop, mask;
for (loop=0,mask=0x80;loop<8;loop++, mask=mask>>1)
{
	gpioSetValue (SOFTSPI_SCLK_PORT, SOFTSPI_SCLK_PIN, 0);
    if (data_out & mask) gpioSetValue (SOFTSPI_MOSI_PORT, SOFTSPI_MOSI_PIN, 1);
     else 	             gpioSetValue (SOFTSPI_MOSI_PORT, SOFTSPI_MOSI_PIN, 0);
	gpioSetValue (SOFTSPI_SCLK_PORT, SOFTSPI_SCLK_PIN, 1);
}
SOFTSPI_SCLK=0;
}

void as1107write8 (unsigned char adress, unsigned char data)
{
	gpioSetValue (SOFTSPI_CS1_PORT, SOFTSPI_CS1_PIN, 0);

	if (MY_DISPLAY){
	  unsigned char i;
	  for(i = 0; i <3; i++)
	  {
		// repeat 3 times for all devices
		write_spi(adress);
		write_spi(data);
	  }
	} else {
		// only once
		write_spi(adress);
		write_spi(data);
	}
	gpioSetValue (SOFTSPI_CS1_PORT, SOFTSPI_CS1_PIN, 1);
}

void as1107write8_device (unsigned char device, unsigned char adress, unsigned char data)
{
	unsigned char i;

	// used write to all
	gpioSetValue (SOFTSPI_CS1_PORT, SOFTSPI_CS1_PIN, 0);
	for (i = 0; i <3; i++){
		if (device == i)
		{	// if device nr is equal to i ==> write data
			write_spi(adress);
			write_spi(data);
		} else {
			// write to noop register
			write_spi(0x00);
			write_spi(0x00);
		}

	}
	gpioSetValue (SOFTSPI_CS1_PORT, SOFTSPI_CS1_PIN, 1);

}
